<script setup>
import { ref } from 'vue'
import { artEditInfoService, artAddInfoService } from '@/api/article'
//表单检验
const ruleForm = ref({
  id: '',
  cate_name: '',
  cate_alias: ''
})
const rules = {
  cate_name: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9]{1,10}$/,
      message: '分类名称必须是 1-10 位且不含特殊符号',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    { required: true, message: '分类别名不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: '分类别名必须是 1-15 位的大小写字母以及数字构成',
      trigger: 'blur'
    }
  ]
}

//子传父进行更新
const emit = defineEmits(['success'])

//发送请求
const changeInfoService = async () => {
  if (ruleForm.value.id) {
    await artEditInfoService(ruleForm.value)
    ElMessage({
      message: '编辑成功',
      type: 'success'
    })
  } else {
    await artAddInfoService(ruleForm.value)
    ElMessage({
      message: '增加成功',
      type: 'success'
    })
  }
  dialogVisible.value = false
  emit('success')
}

const dialogVisible = ref(false)
const showDialog = (obj) => {
  dialogVisible.value = true
  ruleForm.value = obj
}
defineExpose({
  showDialog
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="ruleForm.id ? '编辑分类' : '添加分类'"
    width="500"
  >
    <el-form :model="ruleForm" :rules="rules">
      <el-form-item label="分类名称" prop="cate_name">
        <el-input v-model="ruleForm.cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input v-model="ruleForm.cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changeInfoService"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
